package thread;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/*
 * @author zzr
 * @date: 2025/04/11  16:26
 * @description:
 */
public class ThreadDemo49 {
    public static void main(String[] args) throws InterruptedException {

        // 1.构造方法中传入 10 意思是有 10 个线程
        CountDownLatch count = new CountDownLatch(10);

        // 创建 10 个线程 负责下载
        for (int i = 0; i < 10; i++) {
            int id = i;
            Thread t = new Thread(() -> {
                Random random = new Random();
                int time = (random.nextInt(5) + 1) * 1000;
                System.out.println("线程 " + id + " 开始下载");
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程 " + id + " 结束下载");
                // 2.告诉 CountDownLatch 执行结束了
                count.countDown();
            });
            t.start();
        }

        // 3.通过 await 操作来等待所有任务结束 也就是  count 被调用 10 次了
        count.await();

        System.out.println("所有任务完成啦！！！");
    }
}
